import 'mood_type.dart';
import 'media_attachment.dart';

/// 情绪记录模型类
/// 用于存储用户的情绪记录信息，包括情绪类型、日记内容、媒体附件等
class MoodRecord {
  /// 记录ID
  final int? id;
  
  /// 情绪类型
  final MoodType moodType;
  
  /// 日记内容
  final String? diaryContent;
  
  /// 内容别名（用于兼容性）
  String? get content => diaryContent;
  
  /// 创建时间
  final DateTime createdAt;
  
  /// 更新时间
  final DateTime updatedAt;
  
  /// 关联的媒体附件列表
  final List<MediaAttachment> mediaAttachments;
  
  /// 情绪强度（1-10）
  final int intensity;
  
  /// 标签列表（用于分类和搜索）
  final List<String> tags;
  
  /// 天气信息（可选）
  final String? weather;
  
  /// 位置信息（可选）
  final String? location;

  /// 构造函数
  const MoodRecord({
    this.id,
    required this.moodType,
    this.diaryContent,
    required this.createdAt,
    required this.updatedAt,
    this.mediaAttachments = const [],
    this.intensity = 5,
    this.tags = const [],
    this.weather,
    this.location,
  });

  /// 从Map创建MoodRecord对象
  /// [map] 包含情绪记录数据的Map
  /// [attachments] 关联的媒体附件列表
  factory MoodRecord.fromMap(
    Map<String, dynamic> map, {
    List<MediaAttachment> attachments = const [],
  }) {
    return MoodRecord(
      id: map['id'] as int?,
      moodType: MoodType.fromString(map['mood_type'] as String),
      diaryContent: map['diary_content'] as String?,
      createdAt: DateTime.parse(map['created_at'] as String),
      updatedAt: DateTime.parse(map['updated_at'] as String),
      mediaAttachments: attachments,
      intensity: map['intensity'] as int? ?? 5,
      tags: (map['tags'] as String?)?.split(',').where((tag) => tag.isNotEmpty).toList() ?? [],
      weather: map['weather'] as String?,
      location: map['location'] as String?,
    );
  }

  /// 转换为Map对象，用于数据库存储
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'mood_type': moodType.toString().split('.').last,
      'diary_content': diaryContent,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
      'intensity': intensity,
      'tags': tags.join(','),
      'weather': weather,
      'location': location,
    };
  }

  /// 转换为JSON对象，用于数据导出
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'moodType': moodType.toString().split('.').last,
      'diaryContent': diaryContent,
      'createdAt': createdAt.toIso8601String(),
      'updatedAt': updatedAt.toIso8601String(),
      'intensity': intensity,
      'tags': tags,
      'weather': weather,
      'location': location,
      'mediaAttachments': mediaAttachments.map((attachment) => attachment.toJson()).toList(),
    };
  }

  /// 创建副本，可选择性地更新某些字段
  MoodRecord copyWith({
    int? id,
    MoodType? moodType,
    String? diaryContent,
    DateTime? createdAt,
    DateTime? updatedAt,
    List<MediaAttachment>? mediaAttachments,
    int? intensity,
    List<String>? tags,
    String? weather,
    String? location,
  }) {
    return MoodRecord(
      id: id ?? this.id,
      moodType: moodType ?? this.moodType,
      diaryContent: diaryContent ?? this.diaryContent,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      mediaAttachments: mediaAttachments ?? this.mediaAttachments,
      intensity: intensity ?? this.intensity,
      tags: tags ?? this.tags,
      weather: weather ?? this.weather,
      location: location ?? this.location,
    );
  }

  /// 获取格式化的创建日期字符串
  String get formattedDate {
    return '${createdAt.year}-${createdAt.month.toString().padLeft(2, '0')}-${createdAt.day.toString().padLeft(2, '0')}';
  }

  /// 获取格式化的创建时间字符串
  String get formattedTime {
    return '${createdAt.hour.toString().padLeft(2, '0')}:${createdAt.minute.toString().padLeft(2, '0')}';
  }

  /// 获取格式化的创建日期时间字符串
  String get formattedDateTime {
    return '$formattedDate $formattedTime';
  }

  /// 判断是否有日记内容
  bool get hasDiary => diaryContent != null && diaryContent!.isNotEmpty;

  /// 判断是否有媒体附件
  bool get hasMedia => mediaAttachments.isNotEmpty;

  /// 获取图片附件列表
  List<MediaAttachment> get imageAttachments {
    return mediaAttachments.where((attachment) => attachment.isImage).toList();
  }

  /// 获取音频附件列表
  List<MediaAttachment> get audioAttachments {
    return mediaAttachments.where((attachment) => attachment.isAudio).toList();
  }

  /// 判断是否有图片附件
  bool get hasImages => imageAttachments.isNotEmpty;

  /// 判断是否有音频附件
  bool get hasAudio => audioAttachments.isNotEmpty;

  /// 获取情绪评分（基于情绪类型和强度）
  double get moodScore {
    return (moodType.score * intensity) / 10.0;
  }

  /// 判断是否为今天的记录
  bool get isToday {
    final now = DateTime.now();
    return createdAt.year == now.year &&
        createdAt.month == now.month &&
        createdAt.day == now.day;
  }

  /// 判断是否为本周的记录
  bool get isThisWeek {
    final now = DateTime.now();
    final weekStart = now.subtract(Duration(days: now.weekday - 1));
    return createdAt.isAfter(weekStart.subtract(const Duration(days: 1)));
  }

  /// 判断是否为本月的记录
  bool get isThisMonth {
    final now = DateTime.now();
    return createdAt.year == now.year && createdAt.month == now.month;
  }

  /// 获取日记内容的摘要（前50个字符）
  String get diarySummary {
    if (!hasDiary) return '';
    return diaryContent!.length > 50
        ? '${diaryContent!.substring(0, 50)}...'
        : diaryContent!;
  }

  @override
  String toString() {
    return 'MoodRecord(id: $id, moodType: $moodType, createdAt: $createdAt, intensity: $intensity)';
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is MoodRecord &&
        other.id == id &&
        other.moodType == moodType &&
        other.createdAt == createdAt;
  }

  @override
  int get hashCode {
    return id.hashCode ^ moodType.hashCode ^ createdAt.hashCode;
  }
}